<template>
  <div class="machine-detail-box full-height bg-white scroll scrollbar padding-20" style="width: 200px;border-radius: 6px">
    <div class="flex column justify-between full-height no-wrap">
      <div>
        <div style="width:160px;height:120px;background:rgba(211,211,211,1)" class="border margin-b-20">
          <q-img :src="deviceImage" style="width:160px;height:120px;" v-if="deviceImage" ></q-img>
          <q-img src="statics/img/machine-tool-1.png" style="width:160px;height:120px;" v-else></q-img>
        </div>
        <div class="list">
          <div class="list-item" >设备编号：{{details.assetNumber ? details.assetNumber :  '--'}}
            <q-tooltip>{{details.assetNumber ? details.assetNumber :  '--'}}</q-tooltip>
          </div>
          <div class="list-item">设备名称：{{details.deviceName ? details.deviceName :  '--'}}
            <q-tooltip>{{details.deviceName ? details.deviceName :  '--'}}</q-tooltip>
          </div>
          <div class="list-item" v-if="fromList"> {{ `状态：${judgeStatus(details.status,'name') || '--'}` }}</div>
          <div class="list-item" v-if="fromList">状态时长: <span  style="font-size: 12px" >{{ `${details.statusDuration|| '--'}` }}</span>
            <q-tooltip>{{`${details.statusDuration|| '--'}`}}</q-tooltip>
          </div>
          <div class="list-item" v-if="fromList">管理状态：
            <div class="state-box flex justify-between items-center" style="margin: 8px 0; display:inline">
              <div :style="{ backgroundColor: judgeStatus(this.details.coverStatus, 'other') }"></div>
              <div :style="{ backgroundColor: judgeStatus(this.details.faultStatus,  'other') }"></div>
              <div :style="{ backgroundColor: judgeStatus(this.details.repairStatus, 'other') }"></div>
            </div>
          </div>
          <div class="list-item">设备类型：{{details.deviceTypeDesc ? details.deviceTypeDesc : '--' }}
            <q-tooltip>{{details.deviceTypeDesc ? details.deviceTypeDesc : '--' }}</q-tooltip>
          </div>
          <div class="list-item">设备型号：{{details.deviceModel ? details.deviceModel :  '--'}}
            <q-tooltip>{{details.deviceModel ? details.deviceModel :  '--'}}</q-tooltip>
          </div>
          <div class="list-item" v-if="fromList">操作人员：{{operatorName ? operatorName  : '--'}}
            <q-tooltip>{{operatorName ? operatorName  : '--'}}</q-tooltip>
          </div>
          <div class="list-item" v-if="fromList">技术人员：{{technicianName ? technicianName  : '--'}}
            <q-tooltip>{{technicianName ? technicianName  : '--'}}</q-tooltip>
          </div>
          <div class="list-item cursor-pointer " @click="goDetail">网关ID：<span style="color: #5f77fd">{{details.boxId ? details.boxId :  '--'}}</span>
            <q-tooltip>{{details.boxId ? details.boxId :  '--'}}</q-tooltip>
          </div>
          <div class="list-item">所在位置：{{details.workshopName ? details.workshopName : '--' }}
            <q-tooltip>{{details.workshopName ? details.workshopName : '--' }}</q-tooltip>
          </div>
          <div v-if="currentStop" style="padding: 10px 0;border-bottom: 1px solid #D3D3D3">
            <q-icon class=" iconfont icontubiao-121" style="margin-right: 5px"></q-icon>当前{{ statusList[1].label }}原因
            <div>
              {{currentStop.cause}}
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMachineDetails } from '../../../boot/status-monitor/machine'
import { MomentJsUtils } from '../../../assets/js/util'
import moment from 'moment'
import { boxQueryList } from '../../../boot/miot/list'
import { isNil } from 'lodash'
export default {
  name: 'machine-detail-box',
  computed: {
    ...mapGetters([
      'client', 'permissions', 'statusList'
    ]),
    showRepair () {
      return this.permissions.indexOf(53) > -1
    }
  },
  props: {
    currentStop: {
      type: Object,
      default: () => {}
    },
    operatorName: {
      type: String,
      default: ''
    },
    technicianName: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      details: {
        oldSecond: 0
      },
      deviceImage: '../../../statics/img/machine-tool-1.png',
      statusOptions: [], // 状态源数据
      otherStatusOptions: [], // 管理状态详细
      fromList: {
        type: Boolean,
        default: true
      },
      timerTime: null,
      timer: null, // 计时器
      oldId: null,
      currentDevice: []
    }
  },
  created () {
    this.init()
  },
  beforeDestroy () {
    // 清除定时器
    clearInterval(this.timerTime)
    clearInterval(this.timer)
    // 取消订阅
    this.closeUbscribeTopic()
  },
  mounted () {
    this.timerTime = setInterval(this.updateDuration, 1000)
    this.timer = setInterval(this.getMachineDetails, 300000)
  },
  methods: {
    async goDetail () {
      if (isNil(this.details.boxUcloudNum)) {
        this.$message.warning('网关在网关列表中不存在!')
        return
      }
      const params = {
        deviceType: 1,
        pageNum: 1,
        pageSize: 15,
        boxId: this.details.boxStrId
      }
      const res = await boxQueryList(params)
      const info = res.data.list[0]
      // const isLatestVersion = info.updateVersion === 2
      const oldVersion = !info.updateVersion
      // 如果不在线的话 就不能跳转了
      if (oldVersion) {
        if (info.onLineStatus !== 'ONLINE') {
          this.$message.warning('设备已离线，请检查网关网络')
          return
        }
        this.$router.push({
          name: 'miotDetail',
          query: {
            boxId: info.boxId,
            deployedDate: info.deployedDate,
            boxStatus: info.boxStatus,
            wanCfg: info.wanCfg ? info.wanCfg.toUpperCase() : '',
            onLineStatus: info.onLineStatus,
            _time: new Date().getTime()
          }
        })
      } else {
        this.$router.push({
          name: 'plcDetail',
          query: {
            boxRemark: info.boxRemark,
            boxId: info.ucloudBoxId,
            deployedDate: info.deployedDate,
            boxNum: info.boxId,
            updateVersion: info.updateVersion,
            _time: new Date().getTime()
          }
        })
      }
    },
    /**
     * 订阅并发送消息
     */
    onSubscribe () {
      if (this.client) {
        const id = this.oldId
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.statusTopic.subscribeTopic}${id}`, this.onMessageArrived, { id: `statusTopicDetail_${id}` }
        )// 订阅主题（机床状态）
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      // 分割topic
      let msgBoxIds = message.headers.destination.split('/')
      // 序列化返回msg
      let msg = JSON.parse(message.body).data
      // 获取boxId
      let msgBoxId = msgBoxIds[5]
      // 判断返回的msg是否为状态的msg
      // 状态相关
      if (msgBoxIds[4] === 'status') {
        if ((this.oldId + '') === msgBoxId) {
          // 1加工
          // 非报警状态
          if (msg.statusCode !== this.Enums.MACHINES_STATUS.WARNING.value) {
            // 换线的状态
            if (msg.statusCode === this.Enums.MACHINES_STATUS.CHANGEOVER.value) {
              this.$set(this.details, 'coverStatus', msg.statusCode)
            } else if (msg.statusCode === this.Enums.MACHINES_STATUS.BREAKDOWN.value) { // 故障状态
              const faultStatus = msg.overFlag ? null : msg.statusCode
              this.$set(this.details, 'faultStatus', faultStatus)
            } else if (msg.statusCode === this.Enums.MACHINES_STATUS.REPAIR.value) { // 维修状态
              const repairStatus = msg.overFlag ? null : msg.statusCode
              this.$set(this.details, 'repairStatus', repairStatus)
            } else { // 其它物理状态
              const oldSecond = parseInt(msg.duration)
              this.$set(this.details, 'oldSecond', oldSecond)
              const duration = MomentJsUtils.humanizeDurationPrecisely(moment.duration(oldSecond, 's'), 's')
              this.$set(this.details, 'statusDuration', duration)
              this.$set(this.details, 'status', msg.statusCode)
            }
          }
          this.$emit('changeStatus')
        }
      }
    },
    /**
     * 取消订阅
     */
    closeUbscribeTopic () {
      if (this.oldId) {
        this.client.unsubscribe(`statusTopicDetail_${this.oldId}`)
        this.oldId = null
      }
    },
    // 5分钟重新获取详情
    getMachineDetails () {
      getMachineDetails(this.details.id).then(res => {
        this.details.oldSecond = parseInt(res.data.statusDuration)
        this.details.statusDuration = MomentJsUtils.humanizeDurationPrecisely(moment.duration(this.details.oldSecond, 's'), 's')
        this.$set(this.details, 'status', res.data.status)
        this.$set(this.details, 'repairStatus', res.data.repairStatus)
        this.$set(this.details, 'faultStatus', res.data.faultStatus)
        this.$set(this.details, 'coverStatus', res.data.coverStatus)
      })
    },
    // 获取详情
    getDetails (params) {
      this.details = params
      this.details.boxId = params.boxId.indexOf('_') > -1 ? params.boxId.split('_')[1] : params.boxId
      this.deviceImage = params.deviceImages ? params.deviceImages[0] : this.deviceImage
      this.updateDuration()
      // 初始化websocket
      if (params.fromList) {
        this.oldId = params.id
        this.onSubscribe()
      } else {
        this.closeUbscribeTopic()
        // 清除定时器
        clearInterval(this.timerTime)
      }
    },
    updateDuration () {
      const oldSecond = parseInt(this.details.oldSecond) + 1
      this.$set(this.details, 'oldSecond', oldSecond)
      const duration = MomentJsUtils.humanizeDurationPrecisely(moment.duration(this.details.oldSecond, 's'), 's')
      this.$set(this.details, 'statusDuration', duration)
    },
    /**
     * 过滤状态枚举
     * @param {number} statusCode
     * @param {string} type
     * @return {string}
     */
    // judgeStatus (statusCode) {
    //   let name = ''
    //   this.statusOptions.forEach(o => {
    //     if (o.value === statusCode) {
    //       name = o.label
    //     }
    //   })
    //   return name
    // },
    judgeStatus (statusCode, type) {
      if (type === 'name') {
        let name = ''
        this.statusList.forEach(o => {
          if (o.value + '' === statusCode + '') {
            name = o.label
          }
        })
        return name
      } else {
        let color = ''
        this.otherStatusOptions.forEach(o => {
          if (o.value + '' === statusCode + '') {
            color = o.color
          }
        })
        return color
      }
    },
    /**
     * 初始化数据
     */
    init () {
      let statusOptions = [{
        label: '全部',
        value: null
      }]
      let otherStatusOptions = []
      // 冲状态枚举中取出机场状态数组
      const newArr = Object.entries(this.Enums.MACHINES_STATUS)
        .map(entry => {
          return {
            value: entry[1].value,
            label: entry[1].desc,
            color: entry[1].color
          }
        })
      newArr.forEach((item, index) => {
        if (index < 5) {
          statusOptions.push({
            value: item.value,
            label: item.label,
            color: item.color
          })
        } else {
          otherStatusOptions.push({
            value: item.value,
            label: item.label,
            color: item.color
          })
        }
      })
      this.statusOptions = statusOptions
      this.otherStatusOptions = otherStatusOptions
    },
    getDuration (second = 0) {
      if (second >= 0 && second < 60) {
        let seconds = second
        return {
          duration: seconds,
          unit: '秒'
        }
      } else if (second >= 60 && second < 3600) {
        let minutes = Math.floor(parseInt(second) / 60)
        return {
          duration: minutes,
          unit: '分'
        }
      } else if (second >= 3600 && second < (3600 * 24)) {
        let hours = Math.floor(parseInt(second) / 3600)
        return {
          duration: hours,
          unit: '时'
        }
      } else {
        let days = Math.floor(parseInt(second) / (3600 * 24))
        return {
          duration: days,
          unit: '天'
        }
      }
    },
    // 填写完维修申请
    onRefresh () {}
  }
}
</script>

<style lang="stylus" scoped>
  /deep/ .q-btn{
    padding: 0;
    min-height: 32px!important;
    height: 32px!important;
  }
  .state-box{
    div{
      display:inline-block
      width 10px
      height 10px
      margin-right 5px
      background #d3d3d3
      box-shadow 0px 0px 3px 0px rgba(0, 0, 0, 0.15) inherit
      border-radius 50%
    }
  }
.border{
  border-radius 6px
}
  .list {
    .list-item {
      color #333333
      height 47px
      line-height 47px
      border-bottom 1px solid #D3D3D3
      width 154px
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .display {
    display none
  }
</style>
